<?php

/**
 * User:ayou chow
 * Date: 2019-12-24
 * Time: 22:16
 */

namespace app\common;


use Qcloud\Cos\Client;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Live\V20180801\LiveClient;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamStateRequest;
use TencentCloud\Live\V20180801\Models\DropLiveStreamRequest;

class TXService
{
    /**
     * timelife = 0 时只发送在线用户
     * @param $touid
     * @param $desc
     * @param array $ext
     * @param int $timelife
     * @return mixed
     * @throws \Exception
     */
    public static function sendmsg($touid, $desc, $ext = [], $timelife = 604800)
    {
        $uri = 'v4/openim/sendmsg';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'SyncOtherMachine' => 2,
            'To_Account'       => $touid,
            'MsgRandom'        => rand(1000000, 9999999),
            'MsgTimeStamp'     => time(),
            'MsgLifeTime'      => $timelife,
            'MsgBody'          => [
                0 => [
                    'MsgType'    => 'TIMCustomElem',
                    'MsgContent' => [
                        'Desc' => $desc,
                        'Data' => json_encode($ext)
                    ]
                ]
            ],
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }


    /**
     * 批量发送广播 不会统计到未读消息数量
     * timelife = 0 时只发送在线用户
     * @param $touidArr
     * @param $elem
     * @param int $timelife
     * @return mixed
     * @throws \Exception
     */
    public static function sendBroadcast($touidArr, $elem, $timelife = 604800)
    {
        $uri = 'v4/openim/batchsendmsg';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'SyncOtherMachine' => 2,
            'To_Account'       => $touidArr,
            'MsgRandom'        => rand(1000000, 9999999),
            'MsgTimeStamp'     => time(),
            'MsgLifeTime'      => $timelife,
            'MsgBody'          => [
                0 => $elem
            ],
            'OfflinePushInfo'  => [
                'PushFlag' => 0,
                'Title'    => $elem['MsgContent']['Title'],
                'Desc'     => $elem['MsgContent']['Desc'],
                'Ext'      => $elem['MsgContent']['Data'],
            ],
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 查询账号是否已经导入
     * @param $userid
     * @return mixed
     * @throws \Exception
     */
    public static function acountCheck($userid)
    {

        $uri = 'v4/im_open_login_svc/account_check';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'CheckItem' => [
                ["UserID" => $userid]
            ],
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 创建群聊
     * @param $ownerid
     * @param $groupid
     * @param string $type 群组类型：Private/Public/ChatRoom/AVChatRoom/Community
     * @return mixed
     * @throws \Exception
     */
    public static function createChatRoom($ownerid, $groupid, $type = "AVChatRoom")
    {
        $ret = [];
        $uri = 'v4/group_open_http_svc/create_group';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'Owner_Account' => $ownerid,
            'Type'          => $type,
            'Name'          => $groupid,
            'GroupId'       => $groupid,
        );

        $res = json_decode(httpHelper($api, json_encode($req_data)), true);

        if (empty($res) || !isset($res['ActionStatus']) || !isset($res['ErrorCode'])) {
            $ret['status'] = false;
            $ret['msg'] = json_encode($res);
            return $ret;
        }
        if (($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) || $res['ErrorCode'] == 10021) {
            $ret['status'] = true;
            $ret['msg'] = json_encode($res);
            return $ret;
        }
        $ret['status'] = false;
        $ret['msg'] = json_encode($res);
        return $ret;
    }


    /**
     * 获取群信息
     * @param $group_ids 群组id
     * @info 示例 ['1223333']
     * @return array|mixed
     * @throws \Exception
     */
    public static function getGroupInfo($group_ids)
    {
        if (empty($group_ids)) {
            return array();
        }

        foreach ($group_ids as &$item) {
            $item = (string)$item;
        }

        $uri = 'v4/group_open_http_svc/get_group_info';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'GroupIdList' => $group_ids,
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }


    /**
     * 销毁群组
     * @param $groupid
     * @return mixed
     * @throws \Exception
     */
    public static function destoryChatRoom($groupid)
    {
        $uri = 'v4/group_open_http_svc/destroy_group';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'GroupId' => $groupid,
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 发送聊天室消息
     * @param $groupid
     * @param $elem
     * @return mixed
     * @throws \Exception
     */
    public static function sendChatRoomMsg($groupid, $elem)
    {
        $uri = 'v4/group_open_http_svc/send_group_msg';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            // 'OnlineOnlyFlag' => 1,
            'GroupId'   => $groupid,
            'MsgRandom' => rand(1000000, 9999999),
            'MsgBody'   => [
                $elem
            ],
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 获取用户加入的群组
     * @param $memberid
     * @param string $groupType
     * @return mixed
     * @throws \Exception
     */
    public static function getMemberGroups($memberid, $groupType = "")
    {
        $uri = 'v4/group_open_http_svc/get_joined_group_list';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'GroupType'      => $groupType,
            'Member_Account' => $memberid,
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 移除群组成员
     * @param $groupid
     * @param array $memberid
     * @return mixed
     * @throws \Exception
     */
    public static function deleteGroupMember($groupid, $memberid = [])
    {
        $uri = 'v4/group_open_http_svc/delete_group_member';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'GroupId'             => $groupid,
            'MemberToDel_Account' => $memberid,
            'Silence'             => 1, // 是否静默删除（选填）
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 导入单个账号
     * @param $userid
     * @param $nick_name
     * @param string $avatar
     * @return mixed
     * @throws \Exception
     */
    public static function importAccount($userid, $nick_name, $avatar = '')
    {
        $ret = [];
        $uri = 'v4/im_open_login_svc/account_import';
        $api = self::getTxRequestUrl($uri);



        $req_data = array(
            'UserID'  => $userid,
            'Nick'    => $nick_name,
            'FaceUrl' => $avatar,
        );

        $res = json_decode(httpHelper($api, json_encode($req_data)), true);

        if (empty($res) || !isset($res['ActionStatus']) || !isset($res['ErrorCode'])) {
            $ret['status'] = false;
            $ret['msg'] = json_encode($res);
            $ret['url'] = $api;
            return $ret;
        }
        if (($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0)) {
            $ret['status'] = true;
            $ret['msg'] = json_encode($res);
            return $ret;
        }
        $ret['status'] = false;
        $ret['msg'] = json_encode($res);
        return $ret;
    }

    /**
     * 禁言
     * @param $groupid
     * @param array $userids
     * @param int $shutUpTime
     * @return mixed
     * @throws \Exception
     */
    public static function banUser($groupid, $userids = [], $shutup_Time = 0)
    {
        $uri = 'v4/group_open_http_svc/forbid_send_msg';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'GroupId'  => $groupid,
            'Members_Account'    => $userids,
            'ShutUpTime' => $shutup_Time, //0 取消禁言
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }


    /**
     * 删除账号
     * @param $user_id
     * @return mixed
     * @throws \Exception
     */
    public static function deleteAccount($user_id)
    {
        $uri = 'v4/im_open_login_svc/account_delete';
        $api = self::getTxRequestUrl($uri);

        $req_data = array(
            'DeleteItem'  => [
                ['UserID' => $user_id]
            ],
        );

        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }


    public static function checkPushActive($stream)
    {
        $configPri   = getConfigPri();
        $cred        = new Credential($configPri->qcloud_secretid, $configPri->qcloud_secretkey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("live.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new LiveClient($cred, "", $clientProfile);

        $req = new DescribeLiveStreamStateRequest();

        $params = array(
            "AppName"    => "live",
            "DomainName" => $configPri->push_domain,
            "StreamName" => $stream
        );
        $req->fromJsonString(json_encode($params));

        $resp = $client->DescribeLiveStreamState($req);
        return $resp->getStreamState() == 'active';
    }

    /**
     * @param $file 文件对象  $_FILE
     */
    public static function cosUploadFile()
    {
        $response = [
            'status'   => 1,
            'message'  => '上传失败',
            'img_path' => '',
        ];

        if (!isset($_FILES['file'])) {
            $response['message'] = '没有提交需要上传的文件信息';
            exit;
        }

        //传过来的file
        $file = $_FILES['file'];

        $file_name_arr = explode('.', $_POST['file_name']);
        $file_suffix   = end($file_name_arr);

        $new_name = 'ueditor/image/' . date('Ymd', time()) . '/' . rand(10000000, 99999999) . '.' . $file_suffix;;

        $configPriModel = getConfigPri();
        $param          = [
            'region'      => $configPriModel->cos_region,
            'schema'      => 'http',
            'credentials' => [
                'secretId'  => $configPriModel->qcloud_secretid,
                'secretKey' => $configPriModel->qcloud_secretkey
            ]
        ];

        $body   = fopen($file["tmp_name"], 'rb');
        $client = new Client($param);
        $info   = $client->upload($configPriModel->cos_bucket, $new_name, $body);

        if (isset($info['Location'])) {
            $response['status']   = 0;
            $response['message']  = '上传成功';
            $response['img_path'] = 'https://' . $info['Location'];
        }
        return $response;
    }

    /**
     * 直播断流操作
     * @param $stream_name
     * @return string|void
     */
    public static function dropLiveStream($stream_name)
    {
        $config_primodel = getConfigPri();

        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            $cred = new Credential($config_primodel->qcloud_secretid, $config_primodel->qcloud_secretkey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            // $httpProfile->setProtocol('http://');
            $httpProfile->setEndpoint("live.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);

            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new LiveClient($cred, "", $clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new DropLiveStreamRequest();

            $params = array(
                "StreamName" => $stream_name,
                "DomainName" => $config_primodel->push_domain,
                "AppName"    => "live"
            );
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个DropLiveStreamResponse的实例，与请求对象对应
            $resp = $client->DropLiveStream($req);
            if (isset($resp->Response) && !empty($resp->Response->Error)) {
                return false;
            }

            return true;
        } catch (TencentCloudSDKException $e) {
            // echo $e->getMessage();
            return false;
        }
    }


    /**
     * 组合腾讯im请求地址
     * @param $uri 接口路径uri
     * @throws \Exception
     */
    protected static function getTxRequestUrl($uri)
    {
        $configPri = getConfigPri();
        $configPri->txim_admin = 'admin';
        $tsl_api   = new \Tencent\TLSSigAPIv2($configPri->im_sdkappid, $configPri->im_sdksecret);
        $sig       = $tsl_api->genUserSig($configPri->txim_admin);
        $random    = rand(0, 4294967295);
        $baseUrl   = config('other.tencent_im_api_url');
        $url       = $baseUrl . $uri;
        return $url . "?sdkappid={$configPri->im_sdkappid}&identifier={$configPri->txim_admin}&usersig={$sig}&random={$random}&contenttype=json";
    }
}
